<?php

// Defaults
$Sp_Chr = ',';

// File Data
$f = 1;
$log = null;

$handle = fopen($filename, "x");
$TotalReg = $List[0];
$SUM = 0;
$BNFNOTES = '';
for ($y = 1; $y <= $TotalReg; $y++) {

    $SUM = $SUM + $List[$y]['FraARecibir'];
    $Ag = preg_replace("#[^0-9\-\x\X]#", "", $List[$y]['cb_Sucursal']);
    $Ag = preg_split('/-/', $Ag);
    $LAST = count($Ag) - 1;
    $acc_Type = $List[$y]['TipoCuenta'];
    $log .= $List[$y]['ORInternal'] . $Sp_Chr;
    $log .= date("dmY") . $Sp_Chr;
    $log .= $List[$y]['BnfNombre'] . $Sp_Chr;
    $log .= str_pad($List[$y]['bp_IdBanco'], 4, "0", STR_PAD_LEFT) . $Sp_Chr;
    $log .= str_pad($Ag[0], 6, "0", STR_PAD_LEFT) . $Sp_Chr;
    if ($LAST > 0) {
        $log .= $Ag[$LAST];
    }
    $log .= $Sp_Chr;
    $log .= str_pad(preg_replace("#[^0-9\x\X]#", "", bpcorrconv($List[$y]['cb_Banco'], $List[$y]['CorrNumero'], $List[$y]['cb_Cuenta'], $List[$y]['cb_TipoCuenta'], $List[$y]['cb_Cuenta_prx'], $List[$y]['cb_Cuenta_sux'], $List[$y]['cb_Cuenta_mod'])), 15, "0", STR_PAD_LEFT) . $Sp_Chr;
    $log .= str_pad(preg_replace("#[\-\/\.\ \,]#", "", $List[$y]['BnfCedula']), 14, "0", STR_PAD_LEFT) . $Sp_Chr;
    $log .= str_pad($List[$y]['FraARecibir'], 14, "0", STR_PAD_LEFT) . '00' . $Sp_Chr;
    $log .= $acc_Type[0] . PHP_EOL;
}
$CT = preg_split('/_/', $filename);
$lheader = date("Y") . str_pad($CT[1], 9, "0", STR_PAD_LEFT) . ',' . date("dmY") . ',' . str_pad($TotalReg, 5, "0", STR_PAD_LEFT) . ',' . str_pad($SUM, 16, "0", STR_PAD_LEFT) . '00' . PHP_EOL;

fwrite($handle, $lheader . $log);
fclose($handle);